<template>
  <div class="login">

    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">智能大模型幼儿园教案生成系统</h3>

      <el-form-item prop="username">

        <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="账号"
        >
          <template #prefix><svg-icon icon="user" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="密码"
        >
          <template #prefix><svg-icon icon="password" /></template>
        </el-input>
      </el-form-item>


      <el-checkbox  v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
            size="large"
            type="primary"
            style="width:100%;"
            @click.prevent="handleLogin"
        >
          <span>登 录</span>

        </el-button>

      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
            size="large"
            type="success"
            style="width:100%;"
            @click="showRegisterDialog"
        >
          <span>注 册</span>
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 注册对话框 -->
    <el-dialog
        v-model="registerDialogVisible"
        title="用户注册"
        width="400px"
        :close-on-click-modal="false"
        class="register-dialog"
    >
      <el-form
          ref="registerRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="80px"
          class="register-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="registerForm.phonenumber" placeholder="请输入手机号"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRegister">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--  底部  -->
    <div class="el-login-footer">
      <span></span>
    </div>
  </div>
</template>

<script setup>
  import {ref} from 'vue'
  import requestUtil from '@/util/request'
  import qs from 'qs'
  import {ElMessage} from 'element-plus'
  import Cookies from "js-cookie"
  import { encrypt, decrypt} from "@/util/jsencrypt";
  import router from "@/router"


  const loginForm=ref({
    username:'',
    password:'',
    rememberMe:false
  })

  const loginRef=ref(null)

  const loginRules = {
    username: [{required: true, trigger: "blur", message: "请输入您的账号"}],
    password: [{required: true, trigger: "blur", message: "请输入您的密码"}]
  };

  // 注册相关
  const registerDialogVisible = ref(false)
  const registerRef = ref(null)
  const registerForm = ref({
    username: '',
    password: '',
    email: '',
    phonenumber: ''
  })

  const registerRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phonenumber: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }

  const showRegisterDialog = () => {
    registerDialogVisible.value = true
  }

  const handleRegister = () => {
    registerRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const result = await requestUtil.post('/user/register', registerForm.value)
          if (result.data.code === 200) {
            ElMessage.success('注册成功')
            registerDialogVisible.value = false
            // 清空表单
            registerForm.value = {
              username: '',
              password: '',
              email: '',
              phonenumber: ''
            }
          } else {
            ElMessage.error(result.data.info || '注册失败')
          }
        } catch (error) {
          ElMessage.error('注册失败，请稍后重试')
        }
      } else {
        ElMessage.warning('请填写所有必填项')
      }
    })
  }

  const handleLogin=()=>{
    loginRef.value.validate(async (valid)=>{
      if(valid){
        let result=await requestUtil.post("user/login?"+qs.stringify(loginForm.value))
        console.log(result)
        let data=result.data
        if(data.code===200){
          ElMessage.success(data.info)
          window.sessionStorage.setItem("token",data.token)
          const currentUser = data.user
          currentUser.roles = data.roles
          window.sessionStorage.setItem("currentUser",JSON.stringify(data.user))
          window.sessionStorage.setItem("menuList",JSON.stringify(data.menuList))
          // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
          if (loginForm.value.rememberMe) {
            Cookies.set("username", loginForm.value.username, { expires: 30 });
            Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
            Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
          } else {
          // 否则移除
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          router.replace("/index")
        }else{
          ElMessage.error(data.info)
        }
      }else{
        console.log("验证失败")
      }
    })
  }

  function getCookie() {
    const username = Cookies.get("username");
    const password = Cookies.get("password");
    const rememberMe = Cookies.get("rememberMe");
    loginForm.value = {
      username: username === undefined ? loginForm.value.username : username,
      password: password === undefined ? loginForm.value.password :
          decrypt(password),
      rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
    };
  }
  getCookie();

</script>

<style lang="scss" scoped>
a{
  color:white
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(2px);
  }
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #4A90E2;
  font-size: 28px;
  font-weight: bold;
  text-shadow: 1px 1px 3px rgba(0,0,0,0.1);
  font-family: "Microsoft YaHei", sans-serif;
  background: linear-gradient(45deg, #4A90E2, #87CEEB);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  padding: 10px 0;
}

.login-form {
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.95);
  width: 400px;
  padding: 25px 25px 5px 25px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
  position: relative;
  z-index: 1;
  
  .el-input {
    height: 40px;



    input {
      display: inline-block;
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }

}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}

.register-dialog {
  :deep(.el-dialog__header) {
    text-align: center;
    margin-right: 0;
    padding: 20px;
    background-color: #A3BE8C;
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: white;
      font-size: 18px;
      font-weight: bold;
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 30px 20px;
  }
  
  :deep(.el-form-item__label) {
    font-weight: bold;
    color: #606266;
  }
  
  :deep(.el-input__inner) {
    border-radius: 4px;
  }
  
  :deep(.el-form-item.is-required > .el-form-item__label:before) {
    color: #ff4949;
  }
  
  :deep(.dialog-footer) {
    text-align: center;
    width: 100%;
    display: flex;
    justify-content: center;
    gap: 20px;
  }
}

.el-button--success {
  background-color: #A3BE8C;
  border-color: #A3BE8C;
  
  &:hover, &:focus {
    background-color: #8FAE77;
    border-color: #8FAE77;
  }
}
</style>
